/**
 * Minerva core js
 * - Sets up databases.
 * - Sets up Gears workers and message dispatch for them.
 * - Sets up key press event handlers.
*/

// Namespace
minerva = {};
// Event url
minerva.evurl = '/evs?format=json';

$(function() {
  console.log('minerva.js starting up ...');
  var mercury_status = $('#mercury_status');
  if (!google.gears) {
    // Straight bail if Gears ain't enabled.
    mercury_status.html('You will need to install <a href="http://gears.google.com">Google Gears</a> to experience this site.');
    return;
    }

  // Open database. 
  minerva.db = google.gears.factory.create('beta.database');
  minerva.db.open();

  // NounEvents is a replica of NounEvents in the server datastore
  // that are directed toward user.
  minerva.db.execute('create table if not exists NounEvents' +
      ' (pwun integer, path varchar(255), action varchar(255), creator varchar(255), created float, type varchar(255), title varchar(255))');

  // MercuryFilters is for persisting Mercury filter configurations.
  minerva.db.execute('create table if not exists MercuryFilters' +
      ' (filter_name varchar(255), root varchar(255), types varchar(255), authors varchar(255), keywords varchar(255))');

  // Start worker pool
  minerva.wp = google.gears.factory.create('beta.workerpool');
  // Launch workers
  // Get current js_build number. 
  var js_build = $('#js_build').text();
  var build_ext = '.min' + js_build + '.js';
  console.log('build_ext is:', build_ext);
  // Evsync handles NounEvent syncing
  minerva.evsync_id = minerva.wp.createWorkerFromUrl(
      '/javascript/evsync' + build_ext);
  // Navclouder handles generation of tag cloud data for current location.
  minerva.navclouder_id = minerva.wp.createWorkerFromUrl(
      '/javascript/navclouder' + build_ext);
  // Filterer handles generation of results to be displayed in Mercury.
  minerva.filterer_id = minerva.wp.createWorkerFromUrl(
      '/javascript/filterer' + build_ext);

  // Setup onmessage handler for the main thread
  // This dispatches messages according to sending worker id
  minerva.wp.onmessage = function(text, sid) {
    console.log('Main worker pool got message:', text, sid);
    // First see if this is an ERROR message
    if (text.indexOf('ERROR') == 0) {
      console.log('Error from worker!', sid, text)
      return;
    }

    if (sid == minerva.evsync_id) {
      // Message from evsync, display in jGrowl
      $.jGrowl(text);
      }
    else if (sid == minerva.navclouder_id) {
      // Message from navclouder, display in TagCloud
      var result = JSON.parse(text);
      var parent_path = result[0];
      var cloud_data = result[1];
      var tags = cloud_data[0];
      var pathmap = cloud_data[1];

      var tc = TagCloud.create();
      for (var tagname in tags) {
        tc.add(tagname, tags[tagname], pathmap[tagname]);
        }
      tc.loadEffector('CountSize').base(20).range(10);
      tc.setup('navcloud');
      }
    else if (sid == minerva.filterer_id) {
      // Results message from filterer, display in Mercury
      // We assume that Mercury has been invoked already.
      console.log('Got filter results:', text);
      $('.mercResults').html(text);
      }
    };

  // Setup keydown trigger for evsync start
  $(document).bind('keydown', 'Ctrl+e', function(){
    minerva.wp.sendMessage(minerva.evurl, minerva.evsync_id);
    });

  // Setup keydown trigger for Mercury overlay invocation
  var invokeMercuryOverlay = function() {
    $.mercury_prompt(function(filter_params) {
        minerva.wp.sendMessage(
            JSON.stringify(filter_params), minerva.filterer_id);
        });
    };

  var ctrl_k = 'Ctrl+k';
  $('<span/>')
      .html(ctrl_k)
      .css({'padding-left': '10px'})
      .appendTo(mercury_status);

  $(document).bind('keydown', ctrl_k, invokeMercuryOverlay);
  mercury_status.click(invokeMercuryOverlay);

  // Send message to navclouder to build cloud data for current path.
  console.log('using path', location.pathname);
  minerva.wp.sendMessage(location.pathname, minerva.navclouder_id);
  });
